import { _decorator, Component, Node, RigidBodyComponent, ColliderComponent, Vec3, ICollisionEvent, ITriggerEvent } from 'cc';
import { Group } from '../Common/Constant';
const { ccclass, property } = _decorator;

const v3_0 = new Vec3();
const v3_1 = new Vec3();

@ccclass('MonsterController')
export class MonsterController extends Component {

    private _rigidBody: RigidBodyComponent = null!;
    private _collider: ColliderComponent = null!;
    private _checkCollider: ColliderComponent = null!;

    target: Node = null;
    speedScale: number = 2;

    isDead: boolean = false;
    isAttack: boolean = false;

    onLoad() {
        this._rigidBody = this.getComponent(RigidBodyComponent)!;
        this._collider = this.getComponent(ColliderComponent)!;

        this._checkCollider = this.node.getChildByName("CheckCollider").getComponent(ColliderComponent)!;
    }

    onCollisionEnter(event: ICollisionEvent) {
        if (event.otherCollider.getGroup() == Group.Player) {
            this.isAttack = true;
            this.Attack();
        }
    }

    onCollisionExit(event: ICollisionEvent) {
        if (event.otherCollider.getGroup() == Group.Player) {
            this.isAttack = false;
        }
    }

    onCheckTriggerEnter(event: ITriggerEvent) {
        if (event.otherCollider.getGroup() == Group.Player) {
            this.target = event.otherCollider.node;
        }
    }

    onCheckTriggerExit(event: ITriggerEvent) {
        if (event.otherCollider.getGroup() == Group.Player) {
            this.target = null;
        }
    }

    Attack() {
        console.log(`攻击`);
    }

    Dead() {
        this.isDead = true;
        this._rigidBody.clearVelocity();
    }

    update(deltaTime: number) {
        if (this.target && !this.isDead && !this.isAttack) {
            Vec3.subtract(v3_0, this.target.worldPosition, this.node.worldPosition);
            v3_0.normalize().multiplyScalar(this.speedScale);
            this._rigidBody.setLinearVelocity(v3_0);
        }
    }

    onEnable() {
        this._checkCollider.on('onTriggerEnter', this.onCheckTriggerEnter, this);
        this._checkCollider.on('onTriggerExit', this.onCheckTriggerExit, this);

        this._collider.on('onCollisionEnter', this.onCollisionEnter, this);
        this._collider.on('onCollisionExit', this.onCollisionExit, this);
    }

    onDisable() {
        this._checkCollider.off('onCollisionEnter', this.onCheckTriggerEnter, this);
        this._checkCollider.off('onCollisionExit', this.onCheckTriggerExit, this);
    }
}